<?php

class Payment extends TbAbstract
{

    protected $_table = 'Payment';
    static protected $_instance = null;

	const CONFIRM_FORM = 0;
	const COMFIRM_SLIP = 1;
	
	const SLIP_PATH = 'slips/';
	
	const STATUS_NO = 0;
	const STATUS_PAY = 1;
	const STATUS_MISS = 2;
	const STATUS_NOT_FULLY = 3;

	static private $_id = null;

	static public function getId()
	{
		return self::$_id;
	}

	static public function paymentSlip($file, $invoiceIds)
	{
		$db = Db::getInstance();
		try {
			if(!file_exists($file['tmp_name'])){
				throw new Exception('file not exits');
			}
			$extension = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
			$allowed =  array('gif', 'png', 'jpg');
			if(!in_array($extension, $allowed)){
				throw new Exception('File upload extension not allow (gif, png, jpg)', 1000);
			}
			$sql = "INSERT INTO Payment(confirmType) VALUE(1)";
			if(!$db->query($sql)){
				throw new Exception($db->error);
			}
			$id = $db->insert_id;
			$filename = $id.'.'.$extension;
			$sql = sprintf("UPDATE Payment SET slipPath='%s' WHERE id='%s'",
					$db->real_escape_string($filename),
					$db->real_escape_string($id));
			if(!$db->query($sql)){
				throw new Exception($db->error);
			}
			$insertPI = array();
			foreach ($invoiceIds as $key => $value){
				$insertPI[] = sprintf("('%s','{$id}')", $db->real_escape_string($value));
			}
			$sql = "INSERT INTO PaymentInvoice(invoiceId,paymentId) VALUES".implode(',',$insertPI);
			if(!$db->query($sql)) {
				throw new Exception('Insert PaymentInvoice Error');
			}
			if(!move_uploaded_file($file['tmp_name'], self::SLIP_PATH.$filename)){
				throw new Exception("Can't move upload file");
			}
			self::$_id = $id;
			return true;
		}
		catch(Exception $ex) {
			if($ex->getCode() == 1000){
				throw $ex;
			}
			Log::error($ex->getMessage());
			return false;
		}
	}

	static public function paymentNormal($accountId, $date, $time, $money, $bank, $invoiceIds = array(), $file = null){
		$db = Db::getInstance();
		try {
			$sqlInvoices = array();
			foreach ($invoiceIds as $key => $value){
				$sqlInvoices[] = sprintf("id='%s'", $db->real_escape_string($value));
			}
			$sqlInvoices = 'SELECT (SELECT COUNT(*) FROM Invoice WHERE '.implode(' OR ', $sqlInvoices).') AS c2';
			$sql = $sqlInvoices;
			$result = $db->query($sql);
			$arr = $result->fetch_assoc();

			if($arr['c2'] < count($invoiceIds)){
				throw new Exception('Invalid invoice');
			}
			$sql = sprintf("INSERT INTO Payment(payDate, payTime, money, payBank, confirmType, accountId) VALUES('%s','%s','%s','%s','0','%s')",
					$db->real_escape_string($date),
					$db->real_escape_string($time),
					$db->real_escape_string($money),
					$db->real_escape_string($bank),
					$db->real_escape_string($accountId));
			if(!$db->query($sql)) {
				throw new Exception($db->error);
			}

			$paymentId = $db->insert_id;
			$insertPI = array();
			foreach ($invoiceIds as $key => $value){
				$insertPI[] = sprintf("('%s','{$paymentId}')", $db->real_escape_string($value));
			}
			$sql = "INSERT INTO PaymentInvoice(invoiceId,paymentId) VALUES".implode(',',$insertPI);
			if(!$db->query($sql)) {
				throw new Exception($db->error);
			}
			$query = sprintf("UPDATE Invoice SET status='%s' WHERE id IN('%s') AND status!='%s'",
					$db->real_escape_string(Invoice::STATUS_CHECK),
					implode("','", Db::real_escap_array($invoiceIds)),
					Invoice::STATUS_PAY);
			if(!$db->query($query)) {
				throw new Exception($db->error);
			}
			self::$_id = $paymentId;

			// img
			if(!is_null($file)){
				if(!file_exists($file['tmp_name'])){
					throw new Exception('file not exits');
				}
				$extension = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
				$allowed =  array('gif', 'png', 'jpg');
				if(!in_array($extension, $allowed)){
					throw new Exception('อณุญาตให้ upload ได้แค่ (gif, png, jpg)');
				}

				$id = $paymentId;
				$filename = $id.'.'.$extension;
				$sql = sprintf("UPDATE Payment SET slipPath='%s' WHERE id='%s'",
						$db->real_escape_string($filename),
						$db->real_escape_string($id));
				if(!$db->query($sql)){
					throw new Exception($db->error);
				}
				Log::error($filename);
				if(!move_uploaded_file($file['tmp_name'], self::SLIP_PATH.$filename)){
					throw new Exception("Can't move upload file");
				}
			}
			return true;
		}
		catch(Exception $ex) {
			self::$_id = null;
			Log::error($ex);
			throw $ex;
		}
	}

	static public function getPayments(){
		$db = Db::getInstance();
		$sql = "SELECT * FROM Payment ORDER BY createTime DESC";
		$result = $db->query($sql);
		if(!$result){
			throw new Exception($db->error);
		}
		$arr = array();
		while($row = $result->fetch_assoc()){
			// -----
			$sql2 = sprintf("SELECT PaymentInvoice.* FROM PaymentInvoice
					WHERE paymentId='%s'", $db->real_escape_string($row['id']));
			$result2 = $db->query($sql2);
			if(!$result2){
				throw new Exception($db->error);
			}
			$row['invoices'] = array();
			while($row2 = $result2->fetch_assoc()){
				$invoice = Invoice::getInvoiceById($row2['invoiceId']);
				$row['invoices'][] = $invoice;
			}
			// -----

			$arr[] = $row;
		}
		return $arr;
	}

	static public function getPaymentById($id)
	{
		$db = Db::getInstance();
		try{
			$sql = sprintf("SELECT * FROM Payment WHERE id='%s'", $db->real_escape_string($id));
			$result = $db->query($sql);
			if(!$result || $result->num_rows==0){
				throw new Exception(!$result ? $db->error: 'Not found Payment');
			}
			$payment = $result->fetch_assoc();

			$sql = sprintf("SELECT * FROM PaymentInvoice WHERE paymentId='%s'",$db->real_escape_string($id));
			$result = $db->query($sql);
			if(!$result || $result->num_rows==0){
				throw new Exception(!$result ? $db->error: 'Not found PaymentInvoice');
			}
			while($row = $result->fetch_assoc()){ $invIds[] = $row['invoiceId']; }
			$payment['invoices'] = Invoice::getInvoiceById($invIds);
			return $payment;
		}
		catch(Exception $ex){
			Log::error($ex->getMessage());
			return false;
		}
	}
}